<template>
  <div
    class="sortable-list"
    :style="listStyle"
    @dragstart="onDragStart"
    @dragover.prevent="onDragOver"
    @drop="onDrop"
  >
    <div
      v-for="(item, index) in items"
      :key="item.id"
      class="sortable-item"
      draggable="true"
      :data-index="index"
      @dragstart="handleDragStart"
      @dragend="handleDragEnd"
    >
      <slot :item="item">{{ item.content }}</slot>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const props = defineProps({
  items: {
    type: Array,
    required: true,
    default: () => []
  },
  listStyle: {
    type: Object,
    default: () => ({
      display: 'grid',
      gridTemplateColumns: 'repeat(2, 1fr)', // 每行两个
      gap: '16px'
    })
  }
})

const emits = defineEmits(['update:items'])

const draggedItemIndex = ref(null)

const handleDragStart = (event) => {
  draggedItemIndex.value = Number(event.target.dataset.index)
}

const handleDragEnd = () => {
  draggedItemIndex.value = null
}

const onDragOver = (event) => {
  // Prevent the default behavior to allow dropping
  event.preventDefault()
}

const onDrop = (event) => {
  const targetIndex = Number(event.target.dataset.index)

  if (draggedItemIndex.value !== null && draggedItemIndex.value !== targetIndex) {
    const items = [...props.items]
    const [movedItem] = items.splice(draggedItemIndex.value, 1)
    items.splice(targetIndex, 0, movedItem)

    // Emit the updated list to parent component
    emits('update:items', items)
  }
}

const listStyle = computed(() => ({
  ...props.listStyle
}))
</script>

<style scoped>
.sortable-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr); /* 每行两个 */
  gap: 16px; /* 可以调整间距 */
}

.sortable-item {
  background-color: #fff; /* 示例背景色 */
  border: 1px solid #ddd; /* 示例边框 */
  padding: 16px; /* 示例内边距 */
  cursor: move;
  transition: transform 0.3s ease;
}
</style>
